import store from '../../store'
import mqtt from 'mqtt'
import db from '../../../datastore'

var client
const options = {
    reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
    connectTimeout: 40000, // 40 * 1000毫秒，等待收到CONNACK的时间
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: "",
    password: "",
    clean: true
}

let ws = null // websock
let heart = null // 心跳包定时器id
let isWrong = false // 标记是否密码错误
let isError = false // 标记是否连接错误
var temp = new Array(); // 重连数组



// WebSocket打开回调
// function wsOnOpen (e) {
//     heart = window.setInterval(() => {
//         // console.log('心跳包')
//         wsSend()
//     }, 10000)
//   // 连接成功，在store中标记连接状态
//   isError = false
//     isWrong = false;
   
// }


// 接收WebSocket返回信息
function wsOnMessage(data) {
  // 接收消息，体现在store中
  console.log(data)
  let dataArr = data.split(';')
  dataArr.pop()
  let num = Math.floor((Math.random()*dataArr.length));
  store.commit('user/SET_KID', num)
  console.log(dataArr)
}

// WebSocket关闭回调
function wsClose () {
  if (ws && store.getters.trade) {
    store.dispatch('user/changeTradeStatu', false)
    window.clearInterval(heart)
    isError = false
    heart = null
      client.end()
  } else {
    // eslint-disable-next-line prefer-promise-reject-errors
    console.log('websock对象不存在或未创建')
  }
}
// 初始化客户聊天websock连接
function initkefuWs () {
    // 获取url
    let nodeList = db
        .read()
        .get("trades.lineNode")
        .value();
    let loginUrl = nodeList.filter(v => v.selected)[0];
    console.log(loginUrl.node, 'sdfsdfsdffffff')
    client = mqtt.connect(loginUrl.node, options)
    client.on('connect', (e) => {
        console.log('连接成功:')
        // wsOnOpen()
        // 在线客服列表 customerSerOnline
        client.subscribe('customerSerOnline', (error) => {
            if (!error) {
                console.log('客服列表订阅成功')
            } else {
                console.log('客服列表订阅失败')
            }
        })
        client.subscribe(`chating/customerSer/${store.getters.uid}`, (error) => {
            if (!error) { // 接收消息 chating/customerSer/用户id
                console.log('客户接收消息订阅成功')
            } else {
                console.log('客户接收消息订阅失败')
            }
        })
        client.subscribe(`chating/hisCustomerSer/${store.getters.uid}`, (error) => {
            if (!error) { // 历史数据 chating/hisCustomerSer/用户id
                console.log('客户发送消息订阅成功')
            } else {
                console.log('客户发送消息订阅失败')
            }
        })
    })
    // 接收消息处理
    client.on('message', (topic, message) => {
        wsOnMessage(message.toString())
    })
    // 断开发起重连
    client.on('reconnect', (error) => {
        console.log('客户聊天正在重连:', error)
    })
    // 链接异常处理
    client.on('error', (error) => {
        console.log('客户聊天连接失败:', error)
    })
    client.on('close', (error) => {
        console.log('客户聊天连接关闭:', error)
    })
}

// 发送WebSocket请求
function wsSend (param, content) {
    // alert(client)
    console.log(param, content, client)
    content = content
    client.publish(param, content, {qos: 2})
}

export {
    wsClose,
    initkefuWs,
    wsSend,
    wsOnMessage
}

 